import threading
from datetime import *
import time
import requests
import os

class ThreadDownload(threading.Thread):
    def __init__(self, url, startpos, endpos, f):
        super(ThreadDownload, self).__init__()
        self.url = url
        self.startpos = startpos
        self.endpos = endpos
        self.fd = f
    def dowload(self):
        print("start thread:%s at %s" % (self.getName(), time.time()))
        headers = {"Range": "bytes=%s-%s" % (self.startpos, self.endpos)}
        res = requests.get(self.url, headers=headers)
        self.fd.seek(self.startpos)
        self.fd.write(res.content)
        print("stop thread:%s at %s" % (self.getName(), time.time()))

    def run(self):
        self.dowload()

if __name__ == "__main__":
    url = "http://img.tukuppt.com/video_show/8321488/00/14/41/5e4c01423416b.mp4"
    file_name = url.split('/')[-1]
    file_size = int(requests.get(url).headers['Content-Length'])
    # 线程数
    threadnum = 3
    # 信号量，同时允许线城个数
    threading.BoundedSemaphore(threadnum)
    step = file_size // threadnum
    mtd_list = []
    start = 0
    end = -1
    file_path = 'd:/python/' + str(time.strftime("%Y-%m-%d", time.localtime()))
    if os.path.exists(file_path) == False:
        os.makedirs(file_path)
    # 清空并生成文件
    tempf = open(file_path + '/' + file_name, 'w')
    tempf.close()

    # rb+ , 二进制打开读写
    with open(file_path+ '/' +file_name, 'rb+') as f:
        fileno = f.fileno()
        while end < file_size - 1:
            start = end + 1
            end = start + step - 1
            if end > file_size:
                end = file_size
            dup = os.dup(fileno)
            fd = os.fdopen(dup, 'rb+', -1)
            t = ThreadDownload(url, start, end, fd)
            t.start()
            mtd_list.append(t)
        for i in mtd_list:
            i.join()